//
//  WQ_NetworkManager.swift
//  xinlang
//
//  Created by 联创—王增辉 on 2019/3/25.
//  Copyright © 2019年 lcWorld. All rights reserved.
//

import Moya

struct WQ_NetworkManager<model:Codable> {
    
    typealias WQ_RespneseResult = WQ_NetWorkingResult<model>
    typealias WQNetWorkingCompletion = (_ result:WQ_RespneseResult)->()
    
    func request<T:TargetType>(target:T, GetData:@escaping (_ responseData:[String:Any])->(Any), Completion:@escaping WQNetWorkingCompletion)  {
        
        let provider = MoyaProvider<T>()
        provider.request(target) { (result) in
            switch result {
            case .success(let value):
                do{
                    guard let jsonData = try value.mapJSON() as? [String:Any] else{
                        Completion(WQ_RespneseResult(errorMsg: "返回失败"))
                        return
                    }
                    let jsonDataN = GetData(jsonData)

                    Completion(WQ_RespneseResult(data: jsonDataN))
                }catch{
                    Completion(WQ_RespneseResult(errorMsg: "解析失败"))
                }
                
            case .failure(_):
                Completion(WQ_RespneseResult(errorMsg: "请求失败"))
            }
        }
    }
    func GetTokenRequst(code:String, Completion:@escaping WQNetWorkingCompletion)  {
        request(target: WQ_ServerApi.access_token(code: code), GetData: { (data) -> (Any) in
            return data
        }, Completion: Completion)
    }
    func HomeListRrquest(Completion:@escaping WQNetWorkingCompletion)  {
        request(target: WQ_ServerApi.home_timeline, GetData: { ( value) -> (Any) in
            guard let jsonStr = value["statuses"] as? [[String:Any]] else{
                return []
            }
            return jsonStr
        }, Completion: Completion)
    }
}
